<template>
  <div class="page hidden flex f16">
    <!-- 左侧菜单栏 -->
    <div
      class="aside bg-inverse-theme hidden"
      :class="collapse ? 'aside-collapse' : ''"
    >
      <div class="flex flex-center p10 logo" v-show="!collapse">
        <img src="@/assets/imgs/favicon.png" width="40" alt="" />
        <div class="ml10 f10 text-white text-overflow">GIOET智慧种植</div>
      </div>
      <div
        class="flex flex-center p10 logo f25 text-lighter text-blue-themez"
        v-show="collapse"
      >
        G
      </div>
      <el-menu :default-active="isActive" class="aside-menu bg-inverse-theme">
        <el-menu-item 
        :index="index"  
        v-for="(item, index) in menus" 
        :key="index">
          <router-link 
          :to="'/' + item"
           class="router-link f10"
            @click="setMenuIndex(item,index)">
            <el-icon><component :is="hashMenu[item].icon"></component></el-icon>
            {{ hashMenu[item].text }}
          </router-link>
        </el-menu-item>
      </el-menu>
    </div>
    <!-- 主体部分 -->
    <div class="body flex1 flex flex-col">
      <!-- 头部标题栏 -->
      <div
        ref="header"
        class="header bg-inverse-theme p10 flex flex-between border-box align-center"
      >
        <div class="flex align-center">
          <el-icon
            :size="size"
            v-show="!collapse"
            @click="collapse = true"
            color="#409EFC"
          >
            <Fold />
          </el-icon>
          <el-icon
            :size="size"
            v-show="collapse"
            @click="collapse = false"
            color="#409EFC"
          >
            <Expand />
          </el-icon>

          <el-tag
          v-for="(tag,index) in tags"
          :key="tag.name"
          class="ml10"
          closable
          :effect="tagState == index? 'dark':'plain'"
          size="small"
          @click="goto(tag)"
          @close="removeTag(index)"
          >
          {{tag.name}}
          </el-tag>
          <!-- <router-link 
          v-for="(item,index) in tags"
           :key="index"
           :to="item.url" 
            class="router-link f10">
              {{item.name}}
          </router-link> -->
        </div>
        <div class="flex flex-center">
          <el-image
            class="avatar br100 mlr20"
            :src="userinfo.avatar"
            fit="cover"
          />
          <div class="mr20 text-blue-theme">{{ userinfo.nick_name }}</div>
          <el-button type="primary" @click="showDrawer" size="small">
            进入大屏
          </el-button>
          <el-button type="primary" @click="logout" size="small">
            退出
          </el-button>
        </div>
      </div>
         
      <div class="flex p5 h100 hidden">
        <el-card>
          <!-- 左侧树状级联导航 -->
          <kdSelectTree></kdSelectTree>
        </el-card>
        <el-card class="ml5 flex1" ref="content">
          <!-- 右侧内容部分 -->
          <el-scrollbar :height="contentHeight">
            <router-view></router-view>
          </el-scrollbar>
        </el-card>
      </div>
    </div>

    <!-- 大屏部分 -->
    <el-drawer
      :before-close="setDrawerStorage"
      v-model="drawer"
      direction="ttb"
    >
      <kdlayout :layout="layout">
        <template #kdtitle>
          <bigScreenTitle></bigScreenTitle>
        </template>
        <template #kdweather>
          <kdweather :options="weatherData"></kdweather>
        </template>
        <template #cascade>
          <cascade1></cascade1>
        </template>
        <template #zhongzhi>
          <div class="bigScreenTitle p5">种植品种</div>
        </template>
        <template #gaojing>
          <div class="bigScreenTitle p5">告警统计</div>
        </template>
        <template #shishi>
          <div class="bigScreenTitle p5">实时数据</div>
        </template>
        <template #jihua>
          <div class="bigScreenTitle p5">种植计划</div>
        </template>
      </kdlayout>
    </el-drawer>
    <!-- echarts 弹出框 -->
    <div
      class="echartDrawer br10 f15 ptb10 border-box text-white"
      v-show="echartDrawer"
    >
      <div class="close" @click="echartDrawer = false"></div>
      <div class="text-center mb10">{{ echartData.name }}</div>
      <div class="text-center mb10">{{ echartData.data.address }}</div>
      <div class="mb10">
        <div v-for="(item, index) in echartData.data.children" :key="index">
          <div class="flex mb10">
            <div class="item-label text-right w20">时间：</div>
            <div class="item-text">{{ item.create_time }}</div>
          </div>
          <div class="flex mb10">
            <div class="item-label text-right w20">设施名称：</div>
            <div class="item-text">{{ item.name }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  onMounted,
  watch,
  computed,
  getCurrentInstance,
} from "vue";
import { useStore } from "vuex";
import {useRouter} from 'vue-router'
// import router from "@/router/router";
import layout from "./config.js";

import bigScreenTitle from "@/components/title/title.vue";
import kdweather from "@/components/kdweather/kdweather.vue";
import kdSelectTree from "@/components/kdSelectTree/kdSelectTree.vue";
import cascade1 from "@/components/cascade1/cascade1.vue";

import { formatCountData, getRandom } from "@/utils/index.js";
import chinaJSON from "@/components/chinaJSON";
import {
  mapOpts,
  cropvarOpts,
  msgOpts,
  warningOpts,
  sensorOpts,
} from "./echartsOpts";
import { sensorData } from "./sensorMock";
import { Identification, park } from "./tableHeaderData";
const router = useRouter()
const { proxy } = getCurrentInstance();
const store = useStore();

const content = ref(null);
const collapse = ref(false);
const echartDrawer = ref(false);
const drawer = ref(true);
const size = ref(25);
const isActive = ref(0); //设置当前选中项

const contentHeight = ref(0);
const echartData = reactive({
  data: {
    address: "",
    children: [],
  },
  name: "",
});
const weatherData = reactive({
  degree: 0,
  humidity: 0,
  wind_direction: 0,
  wind_power: 0,
});
// store.state.tags;
const tags = ref([
  // {name:'Tag 1',url:"a"},
])
let menuActive = localStorage.getItem("menuActiveIndex");
tags.value = JSON.parse(localStorage.getItem("breadNavData") || "[]");

location.href.split('/')[2];
// tagState.value = tags.value.findIndex(tag => item.url == '/' + arr[2])
const hashMenu = reactive({
  historyplan: { icon: "setting", text: "种植计划" },
  account: { icon: "document", text: "消息统计" },
  facilities: { icon: "location", text: "设施大屏" },
});
if(menuActive) {
  const arr = menuActive.split("=")
  isActive.value = arr[1] * 1;
  // tags.value.push({
  //   name:hashMenu[arr[0]].text,
  //   url:"/"+ arr[0]
  // })
}
const tagState = ref(0);
const goto = (e) =>{
  console.log(e.url,router);
  router.push(e.url)
  tagState.value = tags.value.findIndex(item=>item.url == e.url)
}
//移除标签
const removeTag = index => {
  // console.log(index,333);
  tags.value.splice(index,1)
  let menuActive = localStorage.getItem("menuActive");
  const arr = menuActive.split("=");
  tagState.value = tags.value.findIndex(tag => item.url == '/' + arr[1])
}
const setMenuIndex = (item,index) =>{
  // JSON.stringify([
  //   {name,url}
  // ])
  //通过点击设置本地存储
  localStorage.setItem("menuActiveIndex",`${item}=${index}`);
  //先取，再存
  const breadNavData = JSON.parse(localStorage.getItem("breadNavData") || "[]");
  const localIndex = breadNavData.findIndex((tag)=> tag.url == "/" + item);
  if(localIndex == -1){
    localStorage.setItem( 
      "breadNavData",
    (breadNavData.push({
     url:'/'+item,
    name:hashMenu[item].text,
  }))
    )
localStorage.setItem("breadNavData",JSON.stringify(breadNavData
  )
   );
  }
  
 tagState.value = tags.value.findIndex((tag)=>tag.url == "/" + item);
  if(tagState.value == -1) {
 tags.value.push({
    url:'/'+item,
    name:hashMenu[item].text
  })
  tagState.value = tags.value.length - 1;
  }
 
  // console.log(item,index,findItem);
}
store.dispatch("getTenantId");

onMounted(() => {
  // 动态设置内容部分的高度
  contentHeight.value = content.value.$el.clientHeight - 10;
});

/* ************************ 通过本地存储获取权限信息,动态设置导航 ************************ */
const userinfo = reactive(JSON.parse(localStorage.getItem("userinfo") || "{}"));
const btnRoles = JSON.parse(localStorage.getItem("roles") || "[]");
const menuData = btnRoles.find((item) => item.name === "index");
const menuName = menuData.children.map((item) => item.name);
const menus = ref(menuName);

/* ************************ 退出登录 ************************ */
const logout = () => {
  localStorage.removeItem("userinfo");
  sessionStorage.removeItem("drawer");
  router.push("/login");
};

/* ************************ 刷新页面后，判断是否需要再次打开大屏界面 ************************ */
if (sessionStorage.getItem("drawer")) {
  drawer.value = false;
}
const showDrawer = () => {
  setDrawerStorage();
  drawer.value = true;
};
const setDrawerStorage = () => {
  drawer.value = false;
  sessionStorage.setItem("drawer", true);
};
watch(
  drawer,
  (e) => {
    console.log(e);
    e ? proxy.fullScreen() : proxy.exitScreen();
  },
  {
    immediate: true,
  }
);
/* ************************ 打开页面就可以直接发送请求，无需传参的请求 ************************ */
// 获取设施数量
(async function () {
  const SensorCount = await proxy.$getSensorCount();
  layout.layoutArr[0].options.data = formatCountData(
    SensorCount.results.split("")
  );
})();

// 获取传感器数量
(async function () {
  const Count = await proxy.$getCount();
  layout.layoutArr[1].options.data = formatCountData(Count.results.split(""));
})();

// 获取天气
(async function () {
  const Weather = await proxy.$getWeather();
  weatherData.degree = Weather.data.observe.degree;
  weatherData.humidity = Weather.data.observe.humidity;
  weatherData.wind_direction = Weather.data.observe.wind_direction;
  weatherData.wind_power = Weather.data.observe.wind_power;
})();

// 获取轮播图数据
(async function () {
  const res = await proxy.$getPhoto();
  layout.layoutArr[5].options.swiperArr = res.results.map((item) => {
    return {
      swiperSlideName: "kdimage",
      options: {
        imgUrl: item,
      },
    };
  });
})();

// 告警统计
(async function () {
  const res = await proxy.$getWarningInfo();
  const xAxis = res.results.map((item) => item.msg_name);
  const yAxis = res.results.map((item) => item.msg_id * 1);
  warningOpts.xAxis["data"] = xAxis;
  warningOpts.series[0]["data"] = yAxis;
  layout.layoutArr[8].options.options = warningOpts;
})();

// 实时数据
(async function () {
  await proxy.$getSensorlastDayData();
  const legend = sensorData.data.map((item) => item.title);
  const xAxis = sensorData.data.map((item) => item.name);
  const series = sensorData.data.map((item, index) => {
    return {
      name: legend[index],
      type: "line",
      stack: "Total",
      data: item.data,
    };
  });
  sensorOpts.legend["data"] = legend;
  sensorOpts.xAxis["data"] = xAxis;
  sensorOpts.series = series;
  layout.layoutArr[10].options.options = sensorOpts;
})();

// 获取地图数据
(async function () {
  const res = await proxy.$getPark();
  mapOpts.series[0].data = res.results.map((item) => {
    const china = chinaJSON.features.find((china) =>
      item.p.address.includes(china.properties.name)
    );
    const arr = china.geometry.coordinates[0];
    return {
      value: arr[getRandom(arr.length)],
      ...item.p,
      ...item,
    };
  });
  layout.layoutArr[14].options = mapOpts;
  layout.layoutArr[14].clickEchart = (e) => {
    if (e.data) {
      Object.assign(echartData, e);
      echartDrawer.value = true;
    }
  };
})();

/* ************************ 监听园区id，当发生变化时，进行请求 ************************ */
// 种植品种
const getCropVarieties = async () => {
  const res = await proxy.$getCropVarieties({
    tenant_id: store.state.tenant_id,
    park_id: store.state.park_id,
  });
  cropvarOpts.series[0].data = res.results;
  layout.layoutArr[6].options.options = cropvarOpts;
};
// 消息
const getMessageCount = async () => {
  const res = await proxy.$getMessageCount({
    park_id: store.state.park_id,
  });
  msgOpts.xAxis["data"] = res.results.map((item) => item.msg_name);
  msgOpts.series[0]["data"] = res.results.map((item) => item.count);
  layout.layoutArr[9].options.options = msgOpts;
};
// 园区种植计划
const getCurrentPlantingPlanListByParkId = async () => {
  const res = await proxy.$getCurrentPlantingPlanListByParkId({
    tenant_id: store.state.tenant_id,
    park_id: store.state.park_id,
  });
  layout.layoutArr[11].options.optionsArr = park;
  layout.layoutArr[11].options.tableData = res.results.map((item, index) => {
    const tools = [];
    if (item) {
      if (item.hasOwnProperty("properties")) {
        item.properties.Node.forEach((node) => {
          node.job.forEach((job) => {
            job.tools.forEach((tool) => {
              tools.push(tool.tool);
            });
          });
        });
      }
    }
    return {
      PlantingPlanName: item?.PlantingPlanName,
      create_time: item?.create_time,
      name: item?.name,
      PhotoURL: item?.PhotoURL,
      job: tools.join("-"),
    };
  });
};
// 获取表格数据
const getIdentificationStaticForEcharts = async () => {
  const res = await proxy.$getIdentificationStaticForEcharts({
    tenant_id: store.state.tenant_id,
    park_id: store.state.park_id,
  });
  layout.layoutArr[12].options.optionsArr = Identification;
  layout.layoutArr[12].options.tableData = res.results.map((item, index) => {
    return {
      id: index + 1,
      ...item,
    };
  });
};
watch(
  computed(() => store.state.park_id),
  (e) => {
    if (!e) {
      return;
    }
    getCropVarieties();
    getMessageCount();
    getCurrentPlantingPlanListByParkId();
    getIdentificationStaticForEcharts();
  }
);

/* ************************ 监听设施id，当发生变化时，进行请求 ************************ */
// 获取摄像头数据
const getCamera = async () => {
  const res = await proxy.$getCamera({
    facilities_id: store.state.facilities,
  });
  layout.layoutArr[13].options.swiperArr = res.results.map((item) => {
    return {
      swiperSlideName: "kdvideo1",
      options: {
        videoSrc: item.p.url_hls,
      },
    };
  });
};
watch(
  computed(() => store.state.facilities),
  (e) => {
    if (!e) {
      return;
    }
    getCamera();
  }
);
</script>

<style lang="scss" scoped>
@import "./index.scss";
</style>
